<!-- 库存结构 -->
<template>
  <div class="wrap-stock-detail">
    <main>
      <n-form ref="formRef" :model="form" :rules="rules" label-placement="left" label-align="right" label-width="120"
        require-mark-placement="right-hanging">
        <n-grid :cols="24" :x-gap="24">
          <n-form-item-gi :span="8" :label="$t('tableColumnLabel.accompanyName')" path="name">
            <n-input v-model:value="form.name" placeholder="请输入陪玩名称" :disabled="disabled" />
          </n-form-item-gi>
          <n-form-item-gi :span="8" :label="$t('tableColumnLabel.gameRank')" path="rank">
            <n-select v-model:value="form.rank" :options="rankDict" placeholder="请输入选择历史段位" :disabled="disabled">
            </n-select>
          </n-form-item-gi>
          <n-form-item-gi :span="8" :label="$t('tableColumnLabel.price')" path="price">
            <n-input-number v-model:value="form.price" :min="0" :max="50000" style="width:100%" :disabled="disabled">
              <template #prefix>
                ￥
              </template>
            </n-input-number>
          </n-form-item-gi>
        </n-grid>
        <n-grid :cols="24" :x-gap="24">
          <n-form-item-gi :span="8" :label="$t('tableColumnLabel.avatarAddress')" path="avatar">
            <n-input v-model:value="form.avatar" placeholder="请输入头像" :disabled="disabled" />
          </n-form-item-gi>
          <n-form-item-gi :span="8" :label="$t('form.accomBirthDay')" path="birthDay">
            <n-date-picker v-model:formatted-value="form.birthDay" placeholder="请输入生日" value-format="yyyy-MM-dd"
              type="date" clearable :disabled="disabled" />
          </n-form-item-gi>
          <n-form-item-gi :span="8" :label="$t('tableColumnLabel.discountPrice')" path="discount">
            <n-input-number v-model:value="form.discount" :min="0" :max="50000" style="width:100%" :disabled="disabled">
              <template #prefix>
                ￥
              </template>
            </n-input-number>
          </n-form-item-gi>
        </n-grid>
        <n-grid :cols="24" :x-gap="24">
          <n-form-item-gi :span="8" :label="$t('tableColumnLabel.sex')" path="sex">
            <n-radio-group v-model:value="form.sex">
              <n-radio-button label="男" value="1">
              </n-radio-button>
              <n-radio-button label="女" value="0">
              </n-radio-button>
            </n-radio-group>
          </n-form-item-gi>
          <n-form-item-gi :span="8" :label="$t('form.accomSignBoard')" path="signboard">
            <n-input v-model:value="form.signboard" :disabled="disabled">
            </n-input>
          </n-form-item-gi>
          <n-form-item-gi :span="8" :label="$t('form.accomBusinessType')" path="type">
            <n-select v-model:value="form.type" :options="businessDict" placeholder="请选择业务类型" :disabled="disabled">
            </n-select>
          </n-form-item-gi>
        </n-grid>
        <n-grid :cols="24" :x-gap="24">
          <n-form-item-gi :span="24" :label="$t('tableColumnLabel.introcution')" path="introduction">
            <n-input type="textarea" maxlength="100" show-count clearable v-model:value="form.introduction"
              placeholder="请输入陪玩介绍" :disabled="disabled" />
          </n-form-item-gi>
        </n-grid>
      </n-form>
    </main>
    <footer>
      <n-button @click="returnBack">{{ $t('button.returnBack') }}</n-button>
      <n-button v-if="!disabled" type="primary"
          @click="handleSave"
          :loading="loading"
          :disabled="loading">{{
          $t('button.save') }}
        </n-button>
    </footer>
  </div>
</template>

<script setup lang='ts'>
import { FormInst, useMessage } from 'naive-ui';
import { updateStock } from '@/api/backend/stock';
import { getByTag } from '@/api/backend/admin';

const emit = defineEmits<{
  (e: 'toList'): void;
}>();
const props = defineProps<{
  detailInfo: {
    type: 'edit' | 'add' | 'view' | null;
    data: Partial<AcompUser>;
  }
}>();
const rules = {
  name: [
    {
      message: '请输入陪玩名称',
      trigger: ['blur', 'input'],
      required: true
    }
  ],
  rank: [
    {
      message: '请选择历史段位',
      trigger: ['input'],
      required: true
    }
  ],
  price: [
    {
      validator(_: any, value?: number) {
        if (value === null || value === undefined) {
          return new Error('需要填写价格！')
        }
        if (value <= 0) {
          return new Error('价格不能小于0')
        }
        return true;
      },
      trigger: ['blur', 'input'],
      required: true
    }
  ],
  avatar: [
    {
      message: '请输入头像地址',
      trigger: ['blur', 'input'],
      required: true
    }
  ],
  birthDay: [
    {
      message: '请输入陪玩生日',
      trigger: ['blur', 'input'],
      required: true
    }
  ],
  discount: [
    {
      validator(_: any, value?: number) {
        if (value === null || value === undefined) {
          return new Error('需要填写折后价格！')
        }
        if (value <= 0) {
          return new Error('折后价格不能小于0')
        }
        return true;
      },
      trigger: ['blur', 'input'],
      required: true
    }
  ],
  sex: [
    {
      message: '请选择陪玩性别',
      trigger: ['input'],
      required: true
    }
  ],
  signboard: [
    {
      message: '请输入陪玩招牌角色',
      trigger: ['blur', 'input'],
      required: true
    }
  ],
  type: [
    {
      message: '请选择业务类型',
      trigger: ['input'],
      required: true
    }
  ],
  introduction: [
    {
      message: '请输入陪玩介绍',
      trigger: ['input'],
      required: true
    }
  ],
}
const formRef = ref<null | FormInst>(null);
const message = useMessage();

const form = reactive<Partial<AcompUserVO>>({});
const loading = ref(false);

const disabled = computed(() => {
  return props.detailInfo.type === 'view';
});

const businessDict = reactive<{
  label: string;
  value: string;
}[]>([]);
const rankDict = reactive<{
  label: string;
  value: string;
}[]>([]);
// 初始化字典
const initDict = async () => {
  try {
    const [res1, res2] = await Promise.all([getByTag('historyRank'), getByTag('businessType')]);
    businessDict.length = 0; // 清空数组
    rankDict.length = 0; // 清空数组
    res1.data.forEach((item: Dict) => {
      rankDict.push({
        label: item.label,
        value: item.value
      });
    });
    res2.data.forEach((item: Dict) => {
      businessDict.push({
        label: item.label,
        value: item.value
      });
    });
  } catch (error) {
    message.error(`获取字典失败-${error}`);
  }
};
initDict()
onMounted(() => {
  if (props.detailInfo.type !== 'add') {
    form.id = props.detailInfo.data.id;
    form.name = props.detailInfo.data.name;
    form.birthDay = props.detailInfo.data.birthDay;
    form.avatar = props.detailInfo.data.avatar;
    form.rank = props.detailInfo.data.rank;
    form.price = props.detailInfo.data.price;
    form.discount = props.detailInfo.data.discount;
    form.signboard = props.detailInfo.data.signboard;
    form.introduction = props.detailInfo.data.introduction
    form.type = props.detailInfo.data.type;
    form.sex = props.detailInfo.data.sex;
  }
});
const handleSave = () => {
  formRef.value?.validate((errors) => {
    if (!errors) {
      updateDate();
    }
    else {
      message.error('请完整输入表单');
    }
  })
};
const updateDate = async () => {
  try {
    loading.value = true;
    const response = await updateStock(form, props.detailInfo.type);
    if (response.code !== 200) throw new Error(response.message);
    message.success('保存成功');
    returnBack();
  } catch (error) {
    message.error(`保存失败: ${error}`);
  } finally {
    loading.value = false;
  }
};

const returnBack = () => {
  emit('toList');
}
</script>
<style scoped lang='scss'>
.wrap-stock-detail {
  display: grid;
  grid-template-rows: 90% 10%;
  height: 100%;

  main {
    padding: 48px 24px;
    overflow: hidden;
  }

  footer {
    height: 100%;
    width: 100%;
    background: rgba(255, 255, 255, 0.2);
    /* 半透明背景 */
    backdrop-filter: blur(10px);
    /* 背景模糊 */
    -webkit-backdrop-filter: blur(10px);
    /* 兼容性前缀 */
    border-top: 1px solid #E7E7E7;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 1rem;
  }
}
</style>